import React,{Component} from 'react';
import { Card,Button,Table, message, Modal,Form,Input,Switch} from 'antd';
import { PlusCircleOutlined } from '@ant-design/icons';
import { reqAttributeListAll,reqAddAttribute ,reqUpdateAttribute,reqUpdateAttributeStatus} from '../../../api/index';
import { saveAttributeActionAll } from '../../../redux/action_creators/course_action'
import {PAGE_SIZE} from '../../../config/index';
import { connect } from 'react-redux';

@connect(
  state=>({course:state.course}),
  {
    saveAttributeListAll:saveAttributeActionAll
  }
)
class Attribute extends Component {
    state={
      attributeListAll:[],  //商品分类列表
      visible:false,  //控制弹窗的展示或隐藏
      operaType:'',  //操作类型?新增:修改
      inputValue:'',  //修改或增加分类输入框内容
      isLoading:true, //table是否显示加载动画
      modelCurrentId:'',
      updateValue:''
    }
      componentDidMount(){
        const {attributeListAll}= this.props.course
        if(attributeListAll.length) this.setState({attributeListAll,isLoading:false}) 
        else this.getAttributeList()
      }
      // 获取课程分类列表
      getAttributeList= async ()=>{
          let result= await reqAttributeListAll()
          const { code, data, msg } = result
          if(code === 200){
            if(data.length===0)  message.success(msg,1)
            this.setState({attributeListAll:data})
            this.props.saveAttributeListAll(data)
            this.setState({isLoading:false})
          }else{
            message.error(msg,1)
            this.setState({isLoading:false})
          }
      }
      // 用于展示新增弹窗
      showAddModal=()=>{
          this.setState({visible:true,operaType:'add',inputValue:''})
      }
      // 用于展示修改弹窗
      showUpdateModal=(attribute)=>{
        this.setState({visible:true,operaType:'update',modelCurrentId:attribute.id,inputValue:attribute.attributeName,updateValue:attribute.attributeName})
    }
    // 新增分类
    toAdd = async() =>{
      this.setState({isLoading:true})
      let result =await reqAddAttribute(this.state.inputValue)
      this.setState({isLoading:false})
      const { data, msg, code} = result;
      if(code === 200) {
        message.success('新增课程属性成功',1)
        let attributeListAll = [...this.state.attributeListAll]
        attributeListAll.unshift(data)
        this.setState({visible:false,attributeListAll})
        this.props.saveAttributeListAll(attributeListAll)
      }else{
        message.error(msg,1)
      }
    }
    // 修改分类
    toUpdate= async()=>{
      const { inputValue,modelCurrentId,updateValue} = this.state
      if(inputValue === updateValue){ 
        //如果修改分类内容没有发什么改变时，点击确定按钮只把弹窗关闭，没有发什么数据交互
        this.setState({visible:false})
      }else{
        const attributeObj = {id:modelCurrentId,attributeName:inputValue}
        let result = await reqUpdateAttribute(attributeObj);
        const {msg,data, code} = result;
        if(code === 200) {
          message.success('修改课程分类成功',1)
          // 修改完成后重新获取分类列表
                let attributeListAll = [...this.state.attributeListAll]
                attributeListAll = attributeListAll.map((item)=> parseInt(item.id) === parseInt( data.id) ? data : item);
                this.setState({attributeListAll,visible:false})
                this.props.saveAttributeListAll(attributeListAll)
        }else{
            message.error(msg,1)
        }
      }
     
    }
    // 点击弹窗ok回调
    handleOk = () => {
      if(this.state.inputValue.length === 0){
        message.warning('请输入分类名称',1)
        return;
      }
      if(this.state.operaType === 'add') this.toAdd()
      if(this.state.operaType === 'update') this.toUpdate()
     
    };
    // 点击取消按钮的回调
    handleCancel = () => {
    this.setState({visible:false})
    };
    // 获取输入框的内容
    changeInputValue=(e)=>{
      this.setState({inputValue:e.target.value})
    }
    // 修改属性状态
    changeStatus=async(id,useStatus)=>{
      console.log(useStatus);
        let attributeListAll = [...this.state.attributeListAll]
        if(useStatus === 1) useStatus = 0
        else useStatus = 1
        let result =await reqUpdateAttributeStatus({id,useStatus})
        const { code,msg} = result
        if(code === 200){
            message.success('分类状态修改成功',1)
            attributeListAll = attributeListAll.map((item)=>{
                if(item.id === id)     item.useStatus = useStatus
                return item;
            })
            this.setState({attributeListAll})
            this.props.saveAttributeListAll(attributeListAll)
        }else{
            message.error(msg,1)
        }
    }
    render(){
        const { operaType, visible , attributeListAll} = this.state;
        const columns = [
            {title: '分类名',
              width:'60%',
              dataIndex: 'attributeName',
              key: 'id',
            },
            { title: '是否启用',
              key: 'id',
              width:'15%',
              render:(item)=>{
                  return(
                      <div>
                          <Switch 
                            checkedChildren="已启用" 
                            unCheckedChildren="未启用" 
                            onClick={()=>this.changeStatus(item.id,item.useStatus)} 
                            defaultChecked={item.useStatus===1?true:false} 
                          />
                      </div>
                  )
              }
            },
            {title: '操作',
            //   dataIndex: 'name',
              key: 'id',
              width:'25%',
              align:'center',
              render:(item)=>{return <Button onClick={()=>{this.showUpdateModal(item)}} type="link">修改分类</Button>}
            }
        ];
        const layout = {  //输入框样式
          wrapperCol: {
            offset: 2,
            span: 20,
          },
        };
        return (
            <div>
                 <Card extra={<Button type="primary" onClick={this.showAddModal}><PlusCircleOutlined/>添加</Button>}>
                 <Table  
                    bordered 
                    dataSource={attributeListAll} 
                    columns={columns}
                    rowKey="id" 
                    pagination={{pageSize:PAGE_SIZE,showQuickJumper :true}}
                    loading={this.state.isLoading}
                />
                </Card>
                <Modal 
                    title={operaType === 'add'? '新增分类':'修改分类'} 
                    visible={visible} 
                    onOk={this.handleOk} 
                    onCancel={this.handleCancel} 
                    okText="确定" 
                    cancelText="取消" 
                    destroyOnClose 
                    closable={false}
                >
                  <Form
                      name="basic"
                      initialValues={{
                          remember: true,
                      }}
                  >
                      <Form.Item
                          name="categoryName"
                          initialValue={this.state.inputValue}
                          {...layout}
                          // rules={[{required: true,message: '分类名称必须输入！',},]}
                      >
                          <Input placeholder="请输入分类名称"  onChange={this.changeInputValue}/>
                      </Form.Item>
                  </Form>
                </Modal>
            </div>
        );
    }
}
export default  Attribute;